package com.hdd.hll.quartz.job;

import com.alibaba.fastjson.JSON;
import com.hdd.hll.common.response.Result;
import com.hdd.hll.common.utils.AesEncryptUtils;
import com.hdd.hll.common.utils.OpenApiLogUtil;
import com.hdd.hll.common.utils.StringUtils;
import com.hdd.hll.modules.truck.web.dto.PassTruckDto;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 车辆推送Job实现类
 *
 * @author jw
 */
@Component
@Slf4j
public class PushPassTruckJob implements Job {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${jd.api.url}")
    private String jdApiUrl;

    @Value("${api.path.suffix.sendTruck.vehicleRelease}")
    private String vehicleRelease;
    ;

    @Override
    public void execute(JobExecutionContext context) {
        Map map = context.getJobDetail().getJobDataMap();
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            // 渠道参数，执行相应的业务流程
            log.info("执行JD调拨单信息同步接口推送任务，入参：{}", entry.getValue());
            Result<String> result = pushPassTruck(JSON.parseObject(entry.getValue(), PassTruckDto.class));
            // 如果成功，移除任务
            if (result.isSuccess()) {
            }
        }
    }


    public Result<String> pushPassTruck(PassTruckDto passTruckDto) {
        StringBuilder dataValidateResult = truckReleaseParamValid(passTruckDto);
        Result<String> result = new Result<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dataValidateResult)) {
            result.setSuccess(false);
            result.setMsg(dataValidateResult.toString());
            OpenApiLogUtil.logResponse(result);
            return result;
        }
        Result<String> decryptRes = null;

        try {
            String vehicleReleaseEncryptRes = restTemplate.postForObject(jdApiUrl + vehicleRelease, AesEncryptUtils.encrypt(JSON.toJSONString(passTruckDto)), String.class);
            decryptRes = JSON.parseObject(AesEncryptUtils.decrypt(vehicleReleaseEncryptRes), Result.class);
            log.info("请求JD车辆放行接口，Msg：{}", decryptRes);
        } catch (Exception e) {
            log.error("请求JD车辆放行接口异常，Msg：{}", e.getMessage());
            if (Objects.isNull(decryptRes)) {
                decryptRes = new Result<>();
            }
            decryptRes.setSuccess(false);
            decryptRes.setCode("500");
            decryptRes.setMsg(String.format("请求JD车辆放行接口异常，Msg：%s", e.getMessage()));
        }
        OpenApiLogUtil.logResponse(decryptRes);
        return decryptRes;
    }

    private StringBuilder truckReleaseParamValid(PassTruckDto passTruckDto) {
        StringBuilder dataValidateResult = new StringBuilder();
        if (StringUtils.isNullOrEmpty(passTruckDto.getMiningDistrictId())) {
            dataValidateResult.append("矿区编号获取异常：miningDistrictId must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(passTruckDto.getMiningDistrict())) {
            dataValidateResult.append("矿区名称获取异常：miningDistrict must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(passTruckDto.getShipmentNo())) {
            dataValidateResult.append("派车单号获取异常：shipmentNo must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(passTruckDto.getLicense())) {
            dataValidateResult.append("车牌号获取异常：license must not be null or empty；");
        }
        if (StringUtils.isNullOrEmpty(passTruckDto.getApprovedTime())) {
            dataValidateResult.append("放行时间获取异常：approvedTime must not be null or empty；");
        }
        return dataValidateResult;
    }
}
